/* 增删改查处理对象
 * @Author: kehua.lsy
 * @Date: 2019-11-19 15:11:21
 * @Last Modified by:   Administrator
 * @Last Modified time: 2019-11-19 15:11:21
 */


export const Crud = {
  data () {
    return {
      //分页参数
      pageParam: {
        currentPage: 1,
        pageSize: 15,
        total: 0
      },
      //弹窗
      dialog: {
        visible: false,//控制是否显示弹窗
        loading: false,//控制是否显示加载动画
      },
      //增删改查接口所需的请求参数
      crudData: {
        postData: null,
        delData: null,
        putData: null,
        getData: null,
      },

    }
  },
  methods: {
    // 增删改查
    crud () {
      let that = this
      return {
        // 增加
        postData () {
          that.api.postData(that.crudData.postData).then((res) => {
            if (res.code == 0) {
              that.crudCallback().getData(res.data)
            } else {
              let text = res.message || '网络出错啦!!!'
              that.crud().message(text)
            }
          })
        },
        // 删除
        delData () {
          that.api.delData(that.crudData.delData).then((res) => {
            if (res.code == 0) {
              that.crudCallback().getData(res.data)
            } else {
              let text = res.message || '网络出错啦!!!'
              that.crud().message(text)
            }
          })
        },
        // 修改
        putData () {
          that.api.putData(that.crudData.putData).then((res) => {
            if (res.code == 0) {
              that.crudCallback().getData(res.data)
            } else {
              let text = res.message || '网络出错啦!!!'
              that.crud().message(text)
            }
          })
        },
        // 查询
        getData () {
          // 这是网络请求时的示例方法
          that.api.getData(that.crudData.getData).then((res) => {
            if (res.code == 0) {
              that.crudCallback().getData(res.data)
            } else {
              let text = res.message || '网络出错啦!!!'
              that.crud().message(text)
            }
          })
        },
        // 网络请求出错时共同触发的弹窗方法
        message (title) {
          that.$message.error(title);
        }
      }
    },
    // 点击分页事件
    callFather () {
      this.mergeData() //合并查询接口参数 
      this.crud().getData() //调用接口
    },

    //增 改
    handleSave (val) {
      let Methods = this.isEdit ? this.request.editMethods : this.request.addMethods
      api[Methods](this.addFields).then((res) => {
        console.log(res)
        this.handleSearchByStatus(res)
        this.dialogFormVisible = false
      }).catch((res) => {
        this.$_c.msg(res.message, { type: 'error' })
      })

    },

    //删
    handleDelete (val) {
      const info = '此操作将删除该记录，确认继续？'
      this.$_c.messageBoxComfirm(info).then((res) => {
        if (res === 0) {
          let ids = [val.data[this.delProp]].join(',')
          api[this.request.delMethods]({ [this.delProp + 's']: ids }).then(res => {
            this.handleSearchByStatus(res)
          })
        }
      })
    },

    //查
    handleSearch () {
      this.loading = true
      //生成请求参数
      let data = Object.assign({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }, this.searchFields)
      api[this.request.getMethods](data).then((res) => {
        // 表格数据赋值
        this.tableData = this.isPager ? res.data[this.dataListField] : res.data;
        // 分页赋值
        this.pageParam.currentPage = res.data.pageNum ? res.data.pageNum : 0;
        this.formInline.pageSize = res.data.pageSize ? res.data.pageSize : 0;
        this.pageParam.total = res.data.total ? res.data.total : 0;
        // 加载结束
        this.loading = false
        //获取数据后对数据进行修饰
        this.handleSearchSuccess && this.handleSearchSuccess()
      }).catch(error => {
        this.tableData = []
        this.loading = false
      })
    },

    //处理批量删除
    handleBatchDelete () {
      const info = '此操作将批量删除所选记录，确认继续？'
      this.$_c.messageBoxComfirm(info).then((res) => {
        if (res === 0) {
          let ids = []
          for (let item of this.multipleSelection) {
            ids.push(item[this.delProp])
          }
          ids = ids.join(',')
          this.$ajax.del(this.url.delData, { [this.delProp + 's']: ids }).then(res => {
            this.handleSearchByStatus(res)
          })
        }
      })
    },

    // 查询条件重置
    handleResetSearch () {
      this.getFieldsFromSearchData()
      this.pageNum = 1
      this.handleSearch()
    },

    //从searchData中提取fields
    getFieldsFromSearchData () {
      if (this.searchFormInfos.children) {
        for (let item of this.searchFormInfos.children) {
          //console.log(item.options)
          if (item.hasOwnProperty('options') && item.options.hasOwnProperty('fields')) {
            for (let i = 0; i < item.options.fields.length; i++) {
              let field = item.options.fields[i]
              let value = (item.options.defaultValue !== undefined && item.options.defaultValue.length == 2) ? (item.options.defaultValue[i] != '' ? new Date(item.options.defaultValue[i]).getTime() : item.options.defaultValue[i]) : ''
              this.$set(this.searchFields, field, value)
            }
          } else if (item.field) {
            this.$set(this.searchFields, item.field, item.options.defaultValue !== undefined ? item.options.defaultValue : '')
          }
        }
      }
      //console.log(this.searchFields)
    },

    //从addData中提取field
    getFieldsFromAddData () {
      if (this.addFormInfos.children) {
        for (let item of this.addFormInfos.children) {
          console.log(item.options)
          if (item.hasOwnProperty('options') && item.options.hasOwnProperty('fields')) {
            for (let i = 0; i < item.options.fields.length; i++) {
              let field = item.options.fields[i]
              let value = (item.options.defaultValue !== undefined && item.options.defaultValue.length == 2) ? (item.options.defaultValue[i] != '' ? new Date(item.options.defaultValue[i]).getTime() : item.options.defaultValue[i]) : ''
              this.$set(this.addFields, field, value)
            }
          } else if (item.field) {
            this.$set(this.addFields, item.field, item.options.defaultValue !== undefined ? item.options.defaultValue : '')
          }
        }
      }
    },

    //获取基础select控件数据
    async getBaseData () {
      let promiseArray = []
      for (let item of this.baseCode) {
        promiseArray.push(this.createPromise(item))
      }
      return await Promise.all(promiseArray)
    },

    createPromise (item) {
      let promise
      const that = this
      promise = new Promise(function (resolve, reject) {
        that.$ajax.get(item.url, item.param).then((res) => {
          if (res.code == 200) {
            let arr = []
            if (res.data instanceof Array) {
              arr.push({ label: '全部', value: '' })
              for (let item of res.data) {
                let baseData = {}
                baseData.label = item
                baseData.value = item
                arr.push(baseData)
              }
            } else {
              arr.push({ label: '全部', value: '' })
              for (let key in res.data) {
                let baseData = {}
                baseData.label = res.data[key]
                baseData.value = key
                arr.push(baseData)
              }
            }

            that.baseData[item.for] = arr
            that.originBaseData[item.for] = res.data
            resolve(0)
          }
        })
      })
      return promise
    },

    //设置field
    changeFields (val) {
      console.log(val)
      if (val.name == 'searchForm') {
        this.searchFields = Object.assign(window._.cloneDeep(this.searchFields), val.field)
      } else if (val.name == 'addForm') {
        this.addFields = Object.assign({}, this.addFields, val.field)
        //if(this.isEdit) this.editData = Object.assign(window._.cloneDeep(this.editData),val.field)
      }
    },

    //处理表单按钮点击
    handleButtonClick (to) {
      //console.log(to)
      if (to.from == 'table') {
        if (to.toDo == 'edit') {
          this.addFields = window._.cloneDeep(to.data)
          this.dialogFormVisible = true
          this.isEdit = true
        } else if (to.toDo == 'del') {
          this.handleDelete(to)//删
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else if (to.from == 'searchForm') {
        if (to.toDo == 'add') {
          this.getFieldsFromAddData()
          this.dialogFormVisible = true
          this.isEdit = false
        } else if (to.toDo == 'search') {
          this.handleSearch()//查
        } else if (to.toDo == 'reset') {
          this.handleResetSearch()
        } else if (to.toDo == 'export') {
          this.handleExport()
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else if (to.from == 'addForm') {
        if (to.toDo == 'save') {
          this.handleSave(to)//增改
        } else if (to.toDo == 'cancel') {
          this.dialogFormVisible = false
          this.addFields = {}
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else if (to.from == 'batchForm') {
        if (to.toDo == 'del') {
          this.handleBatchDelete()
        } else if (to.toDo == 'add') {
          this.dialogFormVisible = true
          this.isEdit = false
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else {
        this.handleOtherClicks && this.handleOtherClicks(to)
      }
      if (this.isEmitBtnsEvents) this.$emit('btns-dto', to)
    },

    //根据状态刷新列表
    handleSearchByStatus (res) {
      if (res.code == 200) {
        this.$_c.msg(res.message)
        this.handleSearch()
      } else {
        this.$_c.msg(res.message, { type: 'error' })
      }
    },

    //处理对话框关闭
    handleDialogClose (val) {
      this.dialogFormVisible = val
    },

    //定时取数据
    handleInterval () {
      clearInterval(this.timer)
      this.handleSearch()
      this.timer = setInterval(() => {
        this.handleSearch()
      }, this.interval)
    },


    // 导出
    handleExport () {
      //this.$_c.msg('导出测试！')
    },

    //处理table选择
    handleSelectionChange (val) {
      this.multipleSelection = val
      this.handleBatchBtnsStatus && this.handleBatchBtnsStatus(val)
    },

    //处理每页显示多少数据
    handleSizeChange (val) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.handleSearch();
    },

    //处理当前页输入
    handleCurrentChange (val) {
      //console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.handleSearch();
    },

    //下载excel,res为要导出的内容，name为文件名
    downloadExcel (res, name) {
      const blob = new Blob([res], {
        type: 'application/vnd.ms-excel;charset=utf-8'
      })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = name + '.xlsx'
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    },
  },
  // mounted () {
  //   this.getFieldsFromSearchData()
  //   if (this.handleSearchBefore) {
  //     this.handleSearchBefore().then(res => {
  //       //console.log(res)
  //       if (res) this.handleSearch()
  //     })
  //   } else {
  //     this.handleSearch()
  //   }
  //   if (this.isOpenInterval) this.handleInterval()
  // },
}
